package com.example.imagesharing;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Typeface;
import android.os.Bundle;
import android.text.InputType;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.android.material.snackbar.Snackbar;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.IOException;
import java.lang.reflect.Type;

import DataBaseHelper.UserDbHelper;
import apimanager.RequestMessage;
import apimanager.ResponseMessage;
import constrants.UserConstrant;
import entity.User;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.Response;
import responsInfo.BaseResponse;
import responsInfo.ErrorResponseInfo;

public class LoginActivity extends AppCompatActivity implements RequestMessage, ResponseMessage {
    private CheckBox rememberPwdCheckBox;
    private UserDbHelper userDbHelper;
    private TextView signUpTextView;
    private TextView userNameView;
    private TextView userPwdView;
    private TextView loginButton;
    private ImageView passVisiableImageView;
    private final String LOGIN_API_PATH = "user/login";
    private final String LOGIN_API_MODE = "POST";
    private boolean pwdVisiable=false;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
//        Intent intent =new Intent(LoginActivity.this,HomeActivity.class);
//        startActivity(intent);
        init();
        showRegisterSuccess();
    }

    private void showRegisterSuccess(){
        Intent intent=getIntent();
        String message=intent.getStringExtra(SignUpActivity.REGISTER_SUCCESS);
        if (message!=null&&message.length()>0) {
            Snackbar.make(findViewById(R.id.act_login), message,
                    Snackbar.LENGTH_SHORT).show();
//                Toast.makeText(LoginActivity.this,message,Toast.LENGTH_SHORT).show();
        }
    }

    private void init() {
        // base init
        rememberPwdCheckBox = findViewById(R.id.cb_remember_pwd);
        userDbHelper = new UserDbHelper(LoginActivity.this);
        signUpTextView = findViewById(R.id.tv_sign_up);
        userNameView = findViewById(R.id.et_account);
        userPwdView = findViewById(R.id.et_pwd);
        loginButton = findViewById(R.id.btn_login);
        passVisiableImageView=findViewById(R.id.iv_pwd_switch);

        // set basic listener
        setPassVisibleClickListener();
        setSignUpButtonClickListener();
        setLoginButtonClickListener();


        // load last username (and password)
        String spFileName = getResources().getString(R.string.last_user_info);
        SharedPreferences spFile = getSharedPreferences(spFileName, MODE_PRIVATE);
        String usernameKey = getResources().getString(R.string.last_username);
        String useridKey = getResources().getString(R.string.last_userid);
        String username = spFile.getString(usernameKey, null);
        String userid = spFile.getString(useridKey, null);
        userNameView.setText(username);

        // load password
        // NOTE: there maybe add the multi user loading so we apply the database to save the user information
        loadPassword(username);
    }

    private void setPassVisibleClickListener(){
        passVisiableImageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                pwdVisiable= !pwdVisiable;
                if (pwdVisiable){
                    passVisiableImageView.setImageResource(R.drawable.y1);
                    userPwdView.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                }
                else {
                    passVisiableImageView.setImageResource(R.drawable.x1);
                    userPwdView.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD|
                            InputType.TYPE_CLASS_TEXT);
                    userPwdView.setTypeface(Typeface.DEFAULT);
                }
            }
        });
    }

    private void setSignUpButtonClickListener() {
        signUpTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(LoginActivity.this, SignUpActivity.class);
                startActivity(intent);
            }
        });
    }

    private void setLoginButtonClickListener() {

        loginButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (userNameView.getText().length() > 0 && userPwdView.getText().length() > 0) {
                    String[] parameters = {"password", userPwdView.getText().toString(),
                            "username", userNameView.getText().toString()};

                    FormBody.Builder builder = new FormBody.Builder();
                    for (int i = 0; i < parameters.length; i += 2) {
                        builder.add(parameters[i], parameters[i + 1]);
                    }
                    FormBody body = builder.build();
                    requestMessage(callback,LOGIN_API_PATH, LOGIN_API_MODE, body);
                } else {
                    Snackbar.make(findViewById(R.id.act_login), "用户名或密码不能为空",
                            Snackbar.LENGTH_SHORT)
                            .show();
                }

            }
        });
    }

    private void loadPassword(String username) {
        runOnUiThread(new Runnable() {
            @SuppressLint("Range")
            @Override
            public void run() {
                SQLiteDatabase db = userDbHelper.getReadableDatabase();
                String[] projection = {UserConstrant.UsersEntry.PASS_WORD};
                if (username != null) {
                    @SuppressLint("Recycle") Cursor cursor = db.query(UserConstrant.UsersEntry.TABLE_NAME,
                            projection,
                            UserConstrant.UsersEntry.USERNAME + "= ?",
                            new String[]{username},
                            null, null, null
                    );
//                    Cursor cursor = db.query(UserConstrant.UsersEntry.TABLE_NAME,
//                            null,null,
//                            null,
//                            null, null, null
//                    );
//                    while (cursor.moveToNext()){
//                        System.out.println("hgjjhgjkhgjkhgjkghjk");
//                        System.out.println(cursor);
//                    }
                    if (cursor.getCount()>0) {
                        int flag=cursor.getColumnIndex(UserConstrant.UsersEntry.PASS_WORD);
                        cursor.moveToNext();
                        @SuppressLint("Range") String pwd = cursor.getString(flag);
                        userPwdView.setText(pwd);
                        rememberPwdCheckBox.setChecked(!pwd.equals(""));
                    }
                } else {
                    rememberPwdCheckBox.setChecked(false);
                }
            }
        });

    }

    private okhttp3.Callback callback=new Callback() {
        @Override
        public void onFailure(@NonNull okhttp3.Call call, @NonNull IOException e) {

            Snackbar.make(findViewById(R.id.act_login), "网络请求出错，请检查网络是否异常或稍后再试",
                    Snackbar.LENGTH_SHORT)
                    .show();
        }

        @Override
        public void onResponse(@NonNull okhttp3.Call call, @NonNull Response response) throws IOException {
            responseMessage(call,response);
        }
    };
    @Override
    public void responseMessage(okhttp3.Call call, Response responseMessageFile) throws IOException {
        final String body = responseMessageFile.body().string();
        Gson gson = new Gson();
//        System.out.println(body);
        if (responseMessageFile.isSuccessful()) {

            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Type jsonType =
                            new TypeToken<BaseResponse<ResponseInfo>>() {
                            }.getType();
                    BaseResponse<ResponseInfo> responseInfo =
                            gson.fromJson(body, jsonType);
                    if (responseInfo.getCode()!=200){
                        Snackbar.make(findViewById(R.id.act_login), responseInfo.getMsg(),
                                Snackbar.LENGTH_SHORT)
                                .show();
                        return;
                    }

                    saveUserInfo(responseInfo);

                    // skip to the homepage
                    Intent intent = new Intent(LoginActivity.this, HomeActivity.class);
                    startActivity(intent);
                }
            });
        } else {
            Type jsonType =
                    new TypeToken<ErrorResponseInfo>() {
                    }.getType();
            ErrorResponseInfo responseInfo =
                    gson.fromJson(body, jsonType);
            Snackbar.make(findViewById(R.id.act_login), responseInfo.getErrorMsg(),
                    Snackbar.LENGTH_SHORT)
                    .show();
        }
    }

    private void saveUserInfo(BaseResponse<ResponseInfo> responseInfo){
        User user = User.getInstance();
        user.setUserId(responseInfo.getData().id);
        user.setAvatar(responseInfo.getData().avatar);
        user.setIntroduce(responseInfo.getData().introduce);
        user.setUsername(responseInfo.getData().username);
        user.setSex(responseInfo.getData().sex == 0 ? "Boy" : "Girl");
        user.setPassword(rememberPwdCheckBox.isChecked() ?  userPwdView.getText().toString():"" );
//        boolean is_che=rememberPwdCheckBox.isChecked();
        ContentValues values = new ContentValues();
        values.put(UserConstrant.UsersEntry.USER_ID, user.getUserId());
        values.put(UserConstrant.UsersEntry.AVATAR, user.getAvatar());
        values.put(UserConstrant.UsersEntry.INTRODUCE, user.getIntroduce());
        values.put(UserConstrant.UsersEntry.USERNAME, user.getUsername());
        values.put(UserConstrant.UsersEntry.SEX, user.getSex());
        values.put(UserConstrant.UsersEntry.PASS_WORD, user.getPassword());

        SQLiteDatabase db_w = userDbHelper.getWritableDatabase();
//        SQLiteDatabase db_r = userDbHelper.getReadableDatabase();
        String[] projection = {UserConstrant.UsersEntry.USERNAME};
        String selection = UserConstrant.UsersEntry.USERNAME+"=?";
        Cursor cursor =db_w.query(UserConstrant.UsersEntry.TABLE_NAME,
                projection,selection,new String[]{user.getUsername()},null,null,null);
        if (cursor.getCount()>0){
            db_w.update(UserConstrant.UsersEntry.TABLE_NAME, values, selection, null);
        }

        else {
            // Gets the data repository in write mode
            long newRowId = db_w.insert(UserConstrant.UsersEntry.TABLE_NAME, null, values);

            // check the process whether can insert data
            if (newRowId < 0) {
                Snackbar.make(findViewById(R.id.act_login), "用户信息保存失败",
                        Snackbar.LENGTH_SHORT)
                        .show();
            }
        }

        // put the last user information into the SharedPreferences for next login
        String spFileName = getResources().getString(R.string.last_user_info);
        String usernameKey = getResources().getString(R.string.last_username);
        String useridKey = getResources().getString(R.string.last_userid);
        SharedPreferences spFile = getSharedPreferences(spFileName, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = spFile.edit();
        editor.putString(useridKey, user.getUserId());
        editor.putString(usernameKey, user.getUsername());
        editor.apply();
    }

    private static class ResponseInfo {
        public String appKey;
        public String avatar;
        public String createTime;
        public String id;
        public String introduce;
        public String lastUpdateTime;
        public String password;
        public int sex;
        public String username;
    }
}
